package cn.gailvlun.gll.chatkit.record;

import android.media.MediaRecorder;

import com.blankj.utilcode.util.FileUtils;

import java.io.IOException;



public class MediaRecorderMgr implements IRecord {

    private static MediaRecorderMgr INSTANCE = null;
    private MediaRecorderMgr() {

    }
    public static MediaRecorderMgr getInstance() {
        if (INSTANCE == null) {
            synchronized (MediaRecorderMgr.class) {
                if (INSTANCE == null) {
                    INSTANCE = new MediaRecorderMgr();
                }
            }
        }
        return INSTANCE;
    }

    private MediaRecorder mediaRecorder;

    @Override
    public void startRecord(String filePath) {
        try {
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mediaRecorder.setOutputFile(filePath);
            mediaRecorder.prepare();
            mediaRecorder.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void pauseRecord() {
    }

    @Override
    public void resumeRecord() {

    }

    @Override
    public void stopRecord() {
        if (mediaRecorder != null) {
            try {
                mediaRecorder.stop();
                mediaRecorder.release();
                mediaRecorder = null;
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void cancelRecord(String filePath) {
        stopRecord();
        FileUtils.deleteFile(filePath);
    }

    @Override
    public void resetRecord() {

    }

    @Override
    public int getVolumeRate() {
        if (mediaRecorder != null) {
            return mediaRecorder.getMaxAmplitude();
        } else {
            return -1;
        }
    }

    @Override
    public void setOnSecondChangeListener(OnSecondChangeListener listener) {

    }
}
